package com.example.cloud.controller.statistics;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.reservation.PatientRepository;
import com.example.cloud.dao.business.reservation.ReservationRepository;
import com.example.cloud.model.business.reservation.Patient;
import com.example.cloud.model.business.reservation.Reservation;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.system.Organ;
import com.example.cloud.model.system.User;
import com.example.cloud.service.system.UserService;
import com.example.cloud.utils.DateUtils;
import com.example.cloud.utils.RequestUtil;
import com.example.cloud.utils.ResultUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * Created by wt on 2018/10/25.
 */
@RestController
@RequestMapping("/statistics")
public class StatisticsController {

    @PersistenceContext
    EntityManager em;

    @Autowired
    private UserService userService;

    @Autowired
    private PatientRepository patientRepository;

    @Autowired
    private ReservationRepository reservationRepository;

    @GetMapping("/reservation/{month}/{userId}")
    public Result reservation(@PathVariable String month, @PathVariable Long userId) throws ParseException {
        List<JSONArray> datas = new ArrayList<>();
        Date date = DateUtils.parseDate(month, new String[]{"yyyy-MM"});
        // 获取当月最后一天
        int lastDay = DateUtils.getLastDayToNumber(date);
        JSONArray colums1 = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("title", month);
        colums1.add(json);
        JSONArray colums2 = new JSONArray();
        json = new JSONObject();
        json.put("title", "姓名");
        colums2.add(json);
        // 查询医护
        List<User> users = new ArrayList<>();
        User u = userService.findOneFromCache(userId);
        if(u != null){
            users.add(u);
        }else{
            User loginUser = RequestUtil.getLoginUser();
            List<Long> organIds = new ArrayList<>();
            List<Organ> organs = loginUser.getOrgans();
            for (Organ organ : organs) {
                organIds.add(organ.getId());
            }
            users = userService.findHealthcareFromCache(organIds);
        }
        for (int i = 1; i <= lastDay; i++) {
            json = new JSONObject();
            json.put("title", i);
            colums1.add(json);
            String ws = "";
            String day = "";
            if (i < 10) {
                day = month + "-0" + i;
            } else {
                day = month + "-" + i;
            }
            int w = DateUtils.getWeek(DateUtils.parseDate(day, new String[]{"yyyy-MM-dd"}));
            if (w == 0) {
                ws = "星期日";
            } else if (w == 1) {
                ws = "星期一";
            } else if (w == 2) {
                ws = "星期二";
            } else if (w == 3) {
                ws = "星期三";
            } else if (w == 4) {
                ws = "星期四";
            } else if (w == 5) {
                ws = "星期五";
            } else if (w == 6) {
                ws = "星期六";
            }
            json = new JSONObject();
            json.put("title", ws);
            colums2.add(json);
        }
        String startDate = month + "-01 00:00:00";
        String endDate = month + "-" + lastDay + " 23:59:59";
//      List<Reservation> list = reservationRepository.findAllByRecordTypeAndAppointmentBetweenAndDeleteFlag(StateConstants.RESERVATION_RECORD_TYPE_RESERVATION, startDate, endDate, 0);
//      StringBuilder sql = new StringBuilder("select * from business_reservation where account_id = :accountId" +
//     " and process in () and status = :status and record_type = :recordType and delete_flag = :deleteFlag and source = :source and parent_id is null and appointment >= '" + startDate + "' and appointment <= '" + endDate + "'");
        
        StringBuilder sql = new StringBuilder("select * from business_reservation where account_id = :accountId" +
          " and status != :status and record_type = :recordType and delete_flag = :deleteFlag and source = :source and parent_id is null and appointment >= '" + startDate + "' and appointment <= '" + endDate + "'");
        Query q = em.createNativeQuery(sql.toString(), Reservation.class);
        q.setParameter("accountId", RequestUtil.getLoginUser().getAccountId());
        //q.setParameter("process", StateConstants.RESERVATION_PROCESS_ARRIVAL);
        q.setParameter("recordType", StateConstants.RESERVATION_RECORD_TYPE_RESERVATION);
        q.setParameter("status", StateConstants.RESERVATION_STATUS_CANCEL);
        q.setParameter("deleteFlag", 0);
        q.setParameter("source", 0);
        List<Reservation> list = q.getResultList();
        for (User user : users) {
            JSONArray data = new JSONArray();
            json = new JSONObject();
            String job = "";
            if (user.getJob().intValue() == StateConstants.USER_JOB_DOCTOR) {
                job = "(医生)";
            } else if (user.getJob().intValue() == StateConstants.USER_JOB_NURSE) {
                job = "(护士)";
            }
            json.put("title", user.getUsername() + job);
            data.add(json);
            for (int i = 1; i <= lastDay; i++) {
                String day = "";
                if (i < 10) {
                    day = "0" + i;
                } else {
                    day = "" + i;
                }
                int count = 0;
                final String temp = day;
                List<Reservation> tempList = list.stream().filter(r -> DateFormatUtils.format(r.getAppointment(), "dd").equals(temp)).collect(toList());
                for (Reservation r : tempList) {
                    if (user.getJob() == StateConstants.USER_JOB_DOCTOR && r.getDoctorId().equals(user.getId())) {
                        count++;
                    } else if (user.getJob() == StateConstants.USER_JOB_NURSE && r.getNurseId().equals(user.getId())) {
                        count++;
                    }
                }
                json = new JSONObject();
                json.put("title", count);
                data.add(json);
            }
            datas.add(data);
        }
        JSONObject result = new JSONObject();
        result.put("colums1", colums1);
        result.put("colums2", colums2);
        result.put("data", datas);
        return ResultUtil.success(result);
    }

    @GetMapping("/patient/{type}")
    public Result patient(@PathVariable int type){
        JSONObject data = new JSONObject();
        User loginUser = RequestUtil.getLoginUser();
        List<Long> organIds = new ArrayList<>();
        for (Organ organ : loginUser.getOrgans()) {
            organIds.add(organ.getId());
        }
        List<Patient> patients = patientRepository.findAllByOrganIdInAndDeleteFlag(organIds, 0);
        if(type == 1){
            Integer[] data1 = new Integer[]{0,0,0,0,0,0,0};
            JSONArray data2 = new JSONArray();
            // 学历统计
            for (Patient patient : patients) {
                if(patient.getCulture() == null){
                    data1[6]++;
                }else if(patient.getCulture() == 0){
                    data1[0]++;
                }else if(patient.getCulture() == 1){
                    data1[1]++;
                }else if(patient.getCulture() == 2){
                    data1[2]++;
                }else if(patient.getCulture() == 3){
                    data1[3]++;
                }else if(patient.getCulture() == 4){
                    data1[4]++;
                }else if(patient.getCulture() == 5){
                    data1[5]++;
                }
            }

            JSONObject json = new JSONObject();
            json.put("value", data1[0]);
            json.put("name", "小学");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[1]);
            json.put("name", "初中");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[2]);
            json.put("name", "高中");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[3]);
            json.put("name", "大学");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[4]);
            json.put("name", "研究生");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[5]);
            json.put("name", "博士生");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[6]);
            json.put("name", "未填写");
            data2.add(json);
            data.put("data1", data1);
            data.put("data2", data2);
        }else if(type == 2){
            Integer[] data1 = new Integer[]{0,0,0,0,0,0,0,0};
            JSONArray data2 = new JSONArray();
            // 职业统计
            for (Patient patient : patients) {
                if(patient.getJob() == null){
                    data1[7]++;
                }else if(patient.getJob() == 0){
                    data1[0]++;
                }else if(patient.getJob() == 1){
                    data1[1]++;
                }else if(patient.getJob() == 2){
                    data1[2]++;
                }else if(patient.getJob() == 3){
                    data1[3]++;
                }else if(patient.getJob() == 4){
                    data1[4]++;
                }else if(patient.getJob() == 5){
                    data1[5]++;
                }else if(patient.getJob() == 6){
                    data1[6]++;
                }
            }

            JSONObject json = new JSONObject();
            json.put("value", data1[0]);
            json.put("name", "公司职员");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[1]);
            json.put("name", "运动员");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[2]);
            json.put("name", "演艺业");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[3]);
            json.put("name", "学生");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[4]);
            json.put("name", "记者");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[5]);
            json.put("name", "公务员");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[6]);
            json.put("name", "其他");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[7]);
            json.put("name", "未填写");
            data2.add(json);
            data.put("data1", data1);
            data.put("data2", data2);
        }else if(type == 3){
            Integer[] data1 = new Integer[]{0,0,0,0,0,0,0,0,0,0,0,0,0};
            JSONArray data2 = new JSONArray();
            // 职业统计
            for (Patient patient : patients) {
                if(patient.getSource() == null){
                    data1[12]++;
                }else if(patient.getSource() == 0){
                    data1[0]++;
                }else if(patient.getSource() == 1){
                    data1[1]++;
                }else if(patient.getSource() == 2){
                    data1[2]++;
                }else if(patient.getSource() == 3){
                    data1[3]++;
                }else if(patient.getSource() == 4){
                    data1[4]++;
                }else if(patient.getSource() == 5){
                    data1[5]++;
                }else if(patient.getSource() == 6){
                    data1[6]++;
                }else if(patient.getSource() == 7){
                    data1[7]++;
                }else if(patient.getSource() == 8){
                    data1[8]++;
                }else if(patient.getSource() == 9){
                    data1[9]++;
                }else if(patient.getSource() == 10){
                    data1[10]++;
                }else if(patient.getSource() == 11){
                    data1[11]++;
                }
            }

            JSONObject json = new JSONObject();
            json.put("value", data1[0]);
            json.put("name", "官方微信");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[1]);
            json.put("name", "官方微博");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[2]);
            json.put("name", "个人微信");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[3]);
            json.put("name", "个人微博");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[4]);
            json.put("name", "官方网站");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[5]);
            json.put("name", "官方APP");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[6]);
            json.put("name", "报纸");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[7]);
            json.put("name", "电视");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[8]);
            json.put("name", "电台");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[9]);
            json.put("name", "朋友介绍");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[10]);
            json.put("name", "家人推荐");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[11]);
            json.put("name", "框架广告");
            data2.add(json);
            json = new JSONObject();
            json.put("value", data1[12]);
            json.put("name", "未填写");
            data2.add(json);
            data.put("data1", data1);
            data.put("data2", data2);
        }
        return ResultUtil.success(data);
    }

    /**
     * 医生财务数据统计
     * @return
     */
    @GetMapping("/doctor")
    public Result doctor(){

        return null;
    }

    /**
     * 护士财务数据统计
     * @return
     */
    @GetMapping("/nurse")
    public Result nurse(){
        return null;
    }
}
